import React, {useEffect, useMemo, useState} from 'react';
import {
    DeleteOutlined, EditOutlined,
    ExclamationCircleOutlined, FolderAddOutlined, FolderOpenOutlined,
} from '@ant-design/icons';
import {
    Breadcrumb,
    Button,
    Form,
    Input,
    Layout,
    message,
    Modal,
    Space,
    Spin
} from "antd";
import {Content} from "antd/es/layout/layout";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import {
    getAllTaskSuiteByPage,
    addSuite,
    getTaskSuiteById,
    modifyTaskSuite,
    deleteTaskSuiteById,
    runTestCase
} from '../../../../../api/taskSuite'
import {addCase, getTestCaseById, modifyTestCase, deleteTestCaseById} from '../../../../../api/testCase'
import {findInterfaceBySystemId} from '../../../../../api/interfaces'
import {getModulesByList} from '../../../../../api/systemModule'
import {getSystemsBySystemId} from '../../../../../api/systemInfo'
import TaskSuiteEditSider from '../../../../../pages/TaskSuiteEditSider'
import TaskSuiteEditContent from '../../../../../pages/TaskSuiteEditContent'

function TaskSuiteEdit(props) {
    const {system_id, task_id} = useParams()
    const navigate = useNavigate()
    const [page, setPage] = useState({
        system_id: Number(system_id),
        task_id: Number(task_id),
        current: 1,
        pageSize: 10
    })
    const location = useLocation()
    const {ids} = location.state
    const [requestData, setRequestData] = useState({
        "json": "{}",
        "headers": [],
        "extracts": [],
        "asserts": [],
        "databaseAsserts": [],
        "params": [],
        "urlencodeds": []
    })
    const [total, setTotal] = useState(0)
    const [response, setResponse] = useState({})
    const [data, setData] = useState([])
    const [suiteForm] = Form.useForm()
    const [caseForm] = Form.useForm()
    const [caseDetailForm] = Form.useForm()
    const [caseInterfaceForm] = Form.useForm()
    const [suitEdit, setSuitEdit] = useState(false)
    const [caseEdit, setCaseEdit] = useState(false)
    const [edit, setEdit] = useState(true)
    const [loading, setLoading] = useState(false);
    const [suiteModalVisible, setSuiteModalVisible] = useState(false);
    const [caseModalVisible, setCaseModalVisible] = useState(false);
    const [interfaceList, setInterfaceList] = useState([])
    const [moduleList, setModuleList] = useState([])
    const [systemInfoList, setSystemInfoList] = useState([]);
    const changeValues = (type)=>{
        setRequestData({...requestData,...type})
    }
    const RunTest= ()=>{
        const values = caseInterfaceForm.getFieldsValue()
        console.log({...values,...requestData})
        runTestCase({...values,...requestData}).then(response=>{
            setResponse(response)
        })
    }
    const AddSuite = () => {
        return (e) => {
            e.stopPropagation();
            setSuiteModalVisible(true)
        }
    }
    const ModifySuite = (key) => {
        return async (e) => {
            e.stopPropagation();
            const {data: res} = await getTaskSuiteById(key)
            suiteForm.setFieldsValue(res.data)
            setSuitEdit(true)
            setSuiteModalVisible(true)
        }
    }
    // 删除套件
    const deleteSuite = (key) => {
        return (e) => {
            e.stopPropagation();
            Modal.confirm({
                title: '删除警告',
                icon: <ExclamationCircleOutlined/>,
                content: '确认要删除套件吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    const {data: res} = await deleteTaskSuiteById(key)
                    message.success(res['msg'])
                    setPage({...page, current: 1})
                }, // 点击确定时要执行的事件
                onCancel: () => {
                    return
                },
            });
        }
    }
    // 删除测试用例
    const deleteCase = (key) => {
        return (e) => {
            e.stopPropagation();
            Modal.confirm({
                title: '删除警告',
                icon: <ExclamationCircleOutlined/>,
                content: '确认要删除用例吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    const {data: res} = await deleteTestCaseById(key)
                    Reset()
                    message.success(res['msg'])
                    setPage({...page})
                }, // 点击确定时要执行的事件
                onCancel: () => {
                    return
                },
            });
        }
    }
    const AddTestCase = (id) => {
        return (e) => {
            e.stopPropagation();
            setCaseModalVisible(true)
            caseForm.setFieldsValue({task_id: Number(task_id), system_id: Number(system_id), task_suite_id: id})
        }
    }
    const ModifyCase = (id) => {
        return async (e) => {
            e.stopPropagation();
            const {data: res} = await getTestCaseById(id)
            caseForm.setFieldsValue(res['data'])
            setCaseEdit(true)
            setCaseModalVisible(true)
        }
    }

    const EditTestCase = async (values) => {
        setLoading(true)
        const {data: res} = await modifyTestCase({...values,request_body:JSON.stringify(requestData)})
        setLoading(false)
        message.success(res['msg'])
    }

    const ChangeTestCase = async (e) => {
        setLoading(true)
        const {data: res} = await getTestCaseById(e['key'])
        const data = res['data'];
        // setCurrentCaseId(Number(e['key']))
        caseDetailForm.setFieldsValue(data)
        caseInterfaceForm.setFieldsValue({
            'path':data['interface_id']?interfaceList.find(i => data['interface_id'] === i.id)['path']:'',
            'method':data['interface_id']?interfaceList.find(i => data['interface_id'] === i.id)['request']:'GET'
        })
        setRequestData(data['request_body']?JSON.parse(data['request_body']):{
            "json": "{}",
            "headers": [],
            "extracts": [],
            "asserts": [],
            "databaseAsserts": [],
            "params": [],
            "urlencodeds": []
        })
        setEdit(false)
        setLoading(false)
    }

    const ChangePage = (e) => {
        setPage({...page, current: e})
    }

    const Reset = () => {
        caseDetailForm.resetFields()
        caseInterfaceForm.resetFields()
        setRequestData({
            "json": "{}",
            "headers": [],
            "extracts": [],
            "asserts": [],
            "databaseAsserts": [],
            "params": [],
            "urlencodeds": []
        })
        setEdit(true)
    }

    useMemo(() => {
        setLoading(true)
        const initData = async () => {
            const {data: res} = await getAllTaskSuiteByPage(page)
            const {total, records} = res.data
            setTotal(total)
            setData(records.map(taskSuite => {
                return {
                    key: taskSuite['id'],
                    icon: <FolderOpenOutlined/>,
                    label: <>{taskSuite['suite_name']}{
                        <Space size={"small"} style={{float: "right"}}>
                            <Button size={"small"} type={"dashed"}
                                    onClick={ModifySuite(taskSuite['id'])}><EditOutlined/></Button>
                            <Button size={"small"} type={"dashed"}
                                    onClick={AddTestCase(taskSuite['id'])}><FolderAddOutlined/></Button>
                            <Button size={"small"} type={"dashed"}
                                    onClick={deleteSuite(taskSuite['id'])}><DeleteOutlined/></Button>
                        </Space>
                    }</>,
                    children: taskSuite['children'].map((testCase) => {
                        return {
                            key: testCase['id'],
                            label: <>{testCase['case_name']}{
                                <Space size={"small"} style={{float: "right"}}>
                                    <Button size={"small"} type={"dashed"}
                                            onClick={ModifyCase(testCase['id'])}><EditOutlined/></Button>
                                    <Button size={"small"} style={{float: "right"}} type={"dashed"}
                                            onClick={deleteCase(testCase['id'])}><DeleteOutlined/></Button>
                                </Space>
                            }</>,
                        };
                    }),
                };
            }))
            setLoading(false)
        }
        initData()
        // eslint-disable-next-line
    }, [page, edit]);

    useEffect(() => {
        const initSelectData = () => {
            findInterfaceBySystemId(system_id).then(response => {
                const {data: res} = response
                setInterfaceList(res['data'])
            })
            getModulesByList({system_id: Number(system_id),ids}).then(response => {
                const {data: res} = response
                setModuleList(res['data'])
            })
            getSystemsBySystemId(system_id).then(response => {
                const {data: res} = response
                setSystemInfoList(res['data'])
            })
        }
        initSelectData()
        // eslint-disable-next-line
    }, [])
    return (
        <Spin spinning={loading}>
            <Layout style={{padding: '0 24px 24px'}}>
                <Breadcrumb style={{margin: '16px 0'}}>
                    <Breadcrumb.Item onClick={() => navigate("/main")}>首頁</Breadcrumb.Item>
                    <Breadcrumb.Item onClick={() => navigate("/main/task")}>任务管理</Breadcrumb.Item>
                    <Breadcrumb.Item onClick={() => navigate(`/main/editTask/${system_id}`)}>编辑任务</Breadcrumb.Item>
                    <Breadcrumb.Item>套件管理</Breadcrumb.Item>
                </Breadcrumb>
                <Layout>
                    <Content
                        style={{
                            margin: 0,
                            minHeight: '80vh',
                        }}
                    >
                        <Layout
                            className="site-layout-background"
                            style={{
                                padding: '24px 0',
                            }}
                        >
                            <TaskSuiteEditSider data={data} AddSuite={AddSuite} ChangeTestCase={ChangeTestCase}
                                                total={total} page={page} ChangePage={ChangePage}/>
                            <TaskSuiteEditContent caseDetailForm={caseDetailForm}
                                                  EditTestCase={EditTestCase}
                                                  system_id={system_id}
                                                  edit={edit}
                                                  Reset={Reset}
                                                  caseInterfaceForm={caseInterfaceForm}
                                                  interfaceList={interfaceList}
                                                  moduleList={moduleList}
                                                  systemInfoList={systemInfoList}
                                                  changeValues={changeValues}
                                                  RunTest={RunTest}
                                                  requestData={requestData}
                                                  response={response}
                            />
                        </Layout>
                    </Content>
                    {/*测试套件模态框*/}
                    <Modal title={suitEdit ? '编辑套件' : '添加套件'} visible={suiteModalVisible} closable={false}
                           footer={null}>
                        <Form
                            name="systemModule"
                            autoComplete="off"
                            layout={'vertical'}
                            form={suiteForm}
                            onFinish={async (values) => {
                                if (suitEdit) {
                                    const {data: res} = await modifyTaskSuite(values)
                                    message.success(res['msg'])
                                } else {
                                    const {data: res} = await addSuite({
                                        ...values,
                                        system_id: Number(system_id),
                                        task_id: Number(task_id)
                                    })
                                    message.success(res['msg'])
                                }
                                setSuiteModalVisible(false)
                                suiteForm.resetFields()
                                setSuitEdit(false)
                                setPage({...page})
                            }}
                        >
                            <Form.Item
                                label="id"
                                name="id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="system_id"
                                name="system_id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="task_id"
                                name="task_id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="套件名称"
                                name="suite_name"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入套件名称',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                wrapperCol={{
                                    offset: 8,
                                    span: 16,
                                }}
                            ><Space>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                                <Button type="default" onClick={async () => {
                                    suiteForm.resetFields()
                                    setSuitEdit(false)
                                    setSuiteModalVisible(false)
                                }}>
                                    取消
                                </Button>
                            </Space>
                            </Form.Item>
                        </Form>
                    </Modal>
                    <Modal title={caseEdit ? '编辑测试用例' : '添加测试用例'} visible={caseModalVisible} closable={false}
                           footer={null}>
                        <Form
                            name="systemModule"
                            autoComplete="off"
                            layout={'vertical'}
                            form={caseForm}
                            onFinish={async (values) => {
                                if (caseEdit) {
                                    const {data: res} = await modifyTestCase(values)
                                    message.success(res['msg'])
                                } else {
                                    const {data: res} = await addCase({
                                        ...values,
                                        system_id: Number(system_id),
                                        task_id: Number(task_id)
                                    })
                                    message.success(res['msg'])
                                }
                                setCaseModalVisible(false)
                                caseForm.resetFields()
                                setCaseEdit(false)
                                setPage({...page})
                            }}
                        >
                            <Form.Item
                                label="id"
                                name="id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="system_id"
                                name="system_id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="task_id"
                                name="task_id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="task_suite_id"
                                name="task_suite_id"
                                style={{display: 'none'}}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="用例名称"
                                name="case_name"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入用例名称',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                wrapperCol={{
                                    offset: 8,
                                    span: 16,
                                }}
                            ><Space>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                                <Button type="default" onClick={async () => {
                                    caseForm.resetFields()
                                    setCaseEdit(false)
                                    setCaseModalVisible(false)
                                }}>
                                    取消
                                </Button>
                            </Space>
                            </Form.Item>
                        </Form>
                    </Modal>
                </Layout>
            </Layout>
        </Spin>
    );
}

export default TaskSuiteEdit;